<template>
  <div class="details">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form label-width="80px" :model="form" :rules="rules" ref="form">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="update">更新</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <component
            :is="'UserInfo'"
            :userInfo="initUser"
            :updateUserinfo="updateUserinfo"
          ></component>
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <component :is="'JobInfo'"></component>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser, sysUserPut } from '@/api/user.js'
export default {
  components: {
    UserInfo: () => import('./components/userInfo.vue'),
    JobInfo: () => import('./components/jobinfo.vue')
  },
  data () {
    return {
      id: this.$route.params.id,
      user: '',
      initUser: {},
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        password: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await sysUser(this.id)
      //   解决聘用形式无值问题
      res.data.formOfEmployees = res.data.formOfEmployees || 1
      this.user = res.data
      //   断开当前页面user与userInfo组件内数据的失联,深拷贝处理数据
      this.initUser = JSON.parse(JSON.stringify(res.data))
      this.form.username = res.data.username
      console.log('当前员工信息', res)
    },
    // 更新按钮点击
    update () {
      this.$refs.form.validate(async result => {
        if (result) {
          await sysUserPut({ ...this.user, ...this.form })
          this.$message.success('更新成功')
          // 修改完当前数据后也要更新原始数据
          this.initUser = { ...this.initUser, ...this.form }
          this.$router.push('/employees')
        }
      })
    },
    // 在子组件更新完用户信息后同步父组件用户信息数据
    updateUserinfo () {
      this.user = JSON.parse(JSON.stringify(this.initUser))
      this.form.username = this.user.username
    }
  }
}
</script>

<style lang="scss" scoped>
.details {
  padding: 15px;
}
</style>
